package com.ebix.sample.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ebix.sample.to.UserTO;

/**
 * Servlet Filter implementation class AuthFilter
 * 
 * by using a filter we can check on a single point every navigation made by the
 * client.
 */
public class AuthFilter implements Filter {

	private String loginPath;
	private String defaultcss;
	private List<String> protectedPaths;

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * we will show that theme for unlogged users
	 * 
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		String msg = "please add init parameter ";
		String x = fConfig.getInitParameter("csstheme");
		if (x == null)
			throw new ServletException(msg + "'csstheme'");
		defaultcss = x;
		x = fConfig.getInitParameter("login-path");
		if (x == null)
			throw new ServletException(msg + "'login-path'");
		loginPath = x;
		x = fConfig.getInitParameter("protected-paths");
		if (x == null)
			throw new ServletException(msg + "'protected-paths'");
		String paths[] = x.split(",");
		int i = paths.length;
		while (i-- > 0)
			paths[i] = paths[i].trim();
		protectedPaths = Arrays.asList(paths);
	}

	/*
	 * utility function to apply the no-cache headers to app protected paths
	 */
	private void setNoCacheHeaders(ServletResponse response) {
		// solving cache problems
		HttpServletResponse res = (HttpServletResponse) response;
		res.setHeader("Cache-Control", "no-cache");
		res.setDateHeader("Expires", 0);
		res.setHeader("Pragma", "No-cache");
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// trying to find the user
		HttpServletRequest req = (HttpServletRequest) request;
		UserTO user = (UserTO) req.getSession().getAttribute("user");
		String path = req.getRequestURL().toString();
		boolean isProtected = false;
		for (String prot : protectedPaths)
			if (path.indexOf(prot) > -1) {
				isProtected = true;
				break;
			}
		if (isProtected) {
			if (user == null) {
				request.setAttribute("pathcss", defaultcss);
				if (path.endsWith(".js")) {
					setNoCacheHeaders(response);
					req.getRequestDispatcher(loginPath + ".js")//
							.forward(request, response);
				} else if (path.endsWith(".jsp")) {
					setNoCacheHeaders(response);
					req.getRequestDispatcher(loginPath + ".jsp")//
							.forward(request, response);
				} else
					chain.doFilter(req, response);
			} else {
				if (path.endsWith(".js") || path.endsWith(".jsp"))
					setNoCacheHeaders(response);
				request.setAttribute("pathcss", user.getTheme());
				chain.doFilter(request, response);
			}
		} else {
			if (user == null)
				request.setAttribute("pathcss", defaultcss);
			else
				request.setAttribute("pathcss", user.getTheme());
			chain.doFilter(req, response);
		}
	}
}
